#!/usr/bin/env python3
"""
场馆容量和活动时间段升级脚本
添加场馆最大容量字段和活动场馆使用时间段字段
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from sqlalchemy import text

def upgrade_venue_capacity():
    """升级场馆和活动表结构"""
    app = create_app()
    
    with app.app_context():
        try:
            print("开始升级场馆和活动表结构...")
            
            # 检查场馆表是否已有max_capacity字段
            result = db.session.execute(text("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'venues'
                AND COLUMN_NAME = 'max_capacity'
            """))
            
            if not result.fetchone():
                # 为场馆表添加最大容量字段
                db.session.execute(text("""
                    ALTER TABLE venues 
                    ADD COLUMN max_capacity INT DEFAULT NULL COMMENT '场馆最大容量（人数）'
                """))
                print("✓ 为场馆表添加了max_capacity字段")
            else:
                print("- 场馆表max_capacity字段已存在")
            
            # 检查活动表是否已有venue_start_time和venue_end_time字段
            result = db.session.execute(text("""
                SELECT COLUMN_NAME 
                FROM INFORMATION_SCHEMA.COLUMNS 
                WHERE TABLE_SCHEMA = DATABASE() 
                AND TABLE_NAME = 'activities'
                AND COLUMN_NAME IN ('venue_start_time', 'venue_end_time')
            """))
            
            existing_venue_time_columns = [row[0] for row in result.fetchall()]
            
            if 'venue_start_time' not in existing_venue_time_columns:
                db.session.execute(text("""
                    ALTER TABLE activities 
                    ADD COLUMN venue_start_time DATETIME COMMENT '场馆预订开始时间'
                """))
                print("✓ 为活动表添加了venue_start_time字段")
            else:
                print("- 活动表venue_start_time字段已存在")
                
            if 'venue_end_time' not in existing_venue_time_columns:
                db.session.execute(text("""
                    ALTER TABLE activities 
                    ADD COLUMN venue_end_time DATETIME COMMENT '场馆预订结束时间'
                """))
                print("✓ 为活动表添加了venue_end_time字段")
            else:
                print("- 活动表venue_end_time字段已存在")
            
            # 提交更改
            db.session.commit()
            print("✅ 数据库升级完成！")
            
        except Exception as e:
            db.session.rollback()
            print(f"❌ 数据库升级失败: {str(e)}")
            raise

if __name__ == '__main__':
    upgrade_venue_capacity() 